package com.mp.approvalreq.servlet.log;

import com.mp.approvalreq.servlet.AbstractServlet;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import org.apache.log4j.NDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Log4jNdcFilter extends AbstractServlet implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        StringBuilder builder = new StringBuilder();
        builder.append("time=").append(System.currentTimeMillis());
        HttpServletRequest req = (HttpServletRequest) request;
        try {
            NDC.push(builder.toString());
            User user = ServiceUtils.getUserInfo(req);
            req.setAttribute("user", user);
            req.setAttribute("language", user.getLanguage());
            builder = new StringBuilder();
            builder.append("][userId=").append(user.getUserId());
            NDC.push(builder.toString());

            parametersReq(req);
            chain.doFilter(request, response);
        } catch (Throwable e) {
            onThrowable(req, (HttpServletResponse) response, e);
        } finally {
            NDC.clear();
        }
    }

    @Override
    public void destroy() {

    }

}
